﻿namespace DesignModeConsole.行为型.观察者模式;

public interface Subject
{
    /// <summary>
    /// 注册观察者
    /// </summary>
    /// <param name="observer"></param>
    void RegisterObserver(Observer observer);

    /// <summary>
    /// 移除观察者
    /// </summary>
    /// <param name="observer"></param>
    void RemoveObserver(Observer observer);

    /// <summary>
    /// 通知观察者
    /// </summary>
    /// <param name="message"></param>
    void NotifyObservers(Message message);
}

/// <summary>
/// 观察者模式实现
/// </summary>
public class ConcreteSubject : Subject
{
    private List<Observer> Observers { get; set; } = new List<Observer>();

    public void RegisterObserver(Observer observer)
    {
        Observers.Add(observer);
    }

    public void RemoveObserver(Observer observer)
    {
        Observers.Remove(observer);
    }

    public void NotifyObservers(Message message)
    {
        foreach (var observer in Observers)
        {
            observer.Update(message);
        }
    }
}

/// <summary>
/// 第一个观察者
/// </summary>
public class ConcreteObserverOne : Observer
{
    public void Update(Message message)
    {
        Console.WriteLine("ConcreteObserverOne 被通知");
    }
}

/// <summary>
/// 第二个观察者
/// </summary>
public class ConcreteObserverTwo : Observer
{
    public void Update(Message message)
    {
        Console.WriteLine("ConcreteObserverTwo 被通知");
    }
}

/// <summary>
/// 观察者接口
/// </summary>
public interface Observer
{
    void Update(Message message);
}

public class Message
{
    public string Content { get; set; }
}